import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 导出excel时后端返回的response.data中只有blob对象,没有data,message,success
    if (response.data instanceof Blob) return response.data // 返回了Blob对象
    const { data, msg, success } = response.data
    // 业务成功，返回数据
    if (success) {
      return data
    } else {
      Message.error(msg)
      return Promise.reject(new Error(msg || 'Error'))
    }
  },
  async error => {
    // 网络请求发生错误 401 404 500
    console.log('err' + error) // for debug
    if (error.response) {
      if (error.response.status === 401) {
        // 清空token和用户信息
        await store.dispatch('user/logout')
        Message.error('token失效请重新登录！')
        router.push('/login')
      } else {
        Message({
          message: error.message,
          type: 'error',
          duration: 5 * 1000
        })
      }
    } else {
      Message.error('网络异常，请稍后再试')
    }
    return Promise.reject(error)
  }
)

export default service
